package ru.kop4en.diplom.camera;

import java.awt.Canvas;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.BufferStrategy;

import javax.swing.JPanel;

import com.googlecode.javacv.VideoInputFrameGrabber;

public class Camera extends JPanel implements Runnable
{
	private static final long serialVersionUID = 1L;
	
	public Camera(int camera_num)
	{
		camera_num_ = camera_num;
		init();
	}
	
	private void init()
	{
		canvas_ = new Canvas()
		{
			/**
			 * 
			 */
			private static final long serialVersionUID = 1L;

			@Override
			public void paint(Graphics g)
			{
				try
				{
					buffer_stat_.show();
				} catch (NullPointerException e)
				{
				} catch (IllegalStateException e)
				{
				}
			}
		};
		
		add(canvas_);
		canvas_.setVisible(true);
		canvas_.createBufferStrategy(1);
		buffer_stat_ = canvas_.getBufferStrategy();
	}
	
	public boolean found()
	{
		grabber_ = new VideoInputFrameGrabber(camera_num_);

		try
		{
			grabber_.start();
		} catch (Exception e)
		{
			return false;
		}
		
		return true;
	}
	
	public void updateSize(boolean need_update)
	{
		need_update_ = need_update;	
	}
	
	@Override
	public void run()
	{
		Image image = null;
		Graphics2D graphics = null;
		while (true)
		{
			try
			{
				image = grabber_.grab().getBufferedImage();				
			} catch (Exception e)
			{				
				e.printStackTrace();
			}
			
			if (image == null)
				return;

			if (buffer_stat_ == null)
				return;
			
			if (need_update_)
			{
				canvas_.setSize(getSize());
				revalidate();
				need_update_ = false;
			}
			
			graphics = (Graphics2D) buffer_stat_.getDrawGraphics();
			graphics.drawImage(image, 0, 0, getWidth(), getHeight(), null);
		}		
	}
	
	// members
	private boolean need_update_ = true;
	private int camera_num_ = 0;
	private Canvas canvas_ = null;
	private VideoInputFrameGrabber grabber_ = null;
	private BufferStrategy buffer_stat_ = null;
}